/**
 * 司机得分对比
 */

import CusModal from '@/components/CusModal';
import iconAdd from '@/img/icon_add.png';
import { LeftOutlined } from '@ant-design/icons';
import { Anchor, Button, message, Spin } from 'antd';
import { FC, ReactElement, useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import AddSearchDriverComp from './AddSearchDriverComp';
import { getDriverSafetyIndexDetail } from './data';
import Ostyle from './index.less';
import ScoreDimensionCmp from './ScoreDimensionCmp';
export type SafeDriverComparisonProps = {};
let selfAllList: any = []; // 用来展示全部指标的
let badBehaAllList: any = [];
let safetyAllList: any = [];
let speedAllList: any = [];
const SafeDriverComparison: FC<SafeDriverComparisonProps> = (): ReactElement => {
  const topRef = useRef<HTMLDivElement>(null);
  const [targetOffset, setTargetOffset] = useState<number>();
  const [urlSearch] = useSearchParams();
  const [loading, setLoading] = useState<boolean>(false);
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; modelType?: string }>({ show: false });
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  const addSearchDriverRef = useRef<any>(null);
  const contentRef = useRef<any>(null);
  // useEffect(() => {
  //   setTargetOffset(topRef.current?.clientHeight);
  // }, []);
  const getCont = () => {
    return document.getElementById('LayoutContent') as HTMLElement;
  };
  const navigator = useNavigate();
  const [topList, setTopList] = useState<any>([]);
  let [selfList, setSelfList] = useState<any>([]); // 司机自身
  let [badBehaList, setBadBehaList] = useState<any>([]); // 驾驶陋习
  let [safetyList, setSafetyList] = useState<any>([]); // 主动安全
  let [speedList, setSpeedList] = useState<any>([]); // 速度相关
  const [showDiffStatus, setShowDiffStatus] = useState<boolean>(false); // true 展示差异中 false 显示全部中
  const [seltedIdArrs, setSeltedIdArrs] = useState<any>([]);
  const showAllFactor = () => {
    setShowDiffStatus(false);
    selfList = [...selfAllList];
    setSelfList([...selfList]);

    badBehaList = [...badBehaAllList];
    setBadBehaList([...badBehaList]);

    safetyList = [...safetyAllList];
    setSafetyList([...safetyList]);

    speedList = [...speedAllList];
    setSpeedList([...speedList]);
  };
  useEffect(() => {
    if (contentRef.current) {
      console.log(contentRef.current, '打印看看ref');
      const handleScroll = () => {
        const sl = document.getElementById('mainContDom') as HTMLElement;
        const aaa = sl.scrollLeft || 0; // 获取滑动距离
        // const bbb = sl.scrollTop || 0; // 获取滑动距离
        const topEle = document.getElementById('topContFixed') as HTMLElement;
        topEle.style.marginLeft = -aaa + 'px'; // 设置元素的偏离距离

        // const leftEle = document.getElementById('leftLinkBtn') as HTMLElement;
        // leftEle.style.marginLeft = -aaa + 'px'; // 设置元素的偏离距离
        // topEle.scrollTo({ left: aaa, behavior: 'smooth' });
        // 这里可以编写处理滚动事件的代码
      };

      contentRef.current.addEventListener('scroll', handleScroll);

      // return () => {
      //   contentRef.current.removeEventListener('scroll', handleScroll);
      // };
    }
  }, []);
  // 处理橙色展示 self提取出来的，所以参数名沿用self***
  const dealOrange = (arr: any, obj: any) => {
    for (let i = 0; i < obj.factorList.length; i++) {
      if (i != 0 && i != obj.factorList.length - 1) {
        let maxValue = arr[0].factorList[i].score;
        let minValue = arr[0].factorList[i].score;
        for (let i2 = 1; i2 < arr.length; i2++) {
          if (arr[i2].factorList[i].score > maxValue) {
            maxValue = arr[i2].factorList[i].score;
          }
          if (arr[i2].factorList[i].score < maxValue) {
            minValue = arr[i2].factorList[i].score;
          }
        }
        arr.forEach((item: any) => {
          if (item.factorList[i].score == maxValue && maxValue != minValue) item.factorList[i].color = 'orange';
        });
      }
    }
  };
  // 添加一项
  const addRowApi = (data: any) => {
    if (showDiffStatus) showAllFactor();
    setLoading(true);
    getDriverSafetyIndexDetail({ driverId: data.driverId }).then((res: any) => {
      if (res && res.code == '200') {
        const obj = {
          driverName: data.driverName,
          starRating: data.starRating,
          driverId: data.driverId,
          aScore: res.data.self.totalScore,
          bScore: res.data.badDrivingHabits.totalScore,
          cScore: res.data.activeSafety.totalScore,
          dScore: res.data.speedDependent.totalScore,
          aTotalScore: 0,
          bTotalScore: 0,
          cTotalScore: 0,
          dTotalScore: 0,

          totalScorc:
            res.data.selfScore > res.data.behaviorTotalScore ? res.data.selfScore : res.data.behaviorTotalScore,
          // eScore: 500,
          gradeColorShape: res.data.gradeColorShape,
        };
        res.data.self.factorList.forEach((el: any) => {
          obj.aTotalScore += el.maxScore;
        });
        res.data.badDrivingHabits.factorList.forEach((el: any) => {
          obj.bTotalScore += el.maxScore;
        });
        res.data.activeSafety.factorList.forEach((el: any) => {
          obj.cTotalScore += el.maxScore;
        });
        res.data.speedDependent.factorList.forEach((el: any) => {
          obj.dTotalScore += el.maxScore;
        });

        topList.push(obj);
        setTopList([...topList]);
        seltedIdArrs.push(data.driverId);
        setSeltedIdArrs([...seltedIdArrs]);
        //列表正式数据
        const selfOjb: any = {
          factorList: res.data.self.factorList,
          totalScore: res.data.self.totalScore,
        };
        selfOjb.factorList.unshift({
          factorName: '司机相关',
          score: '',
          isFirst: true,
        });
        selfOjb.factorList.push({
          factorName: '司机相关合计',
          score: res.data.self.totalScore,
          isTotal: true,
        });

        const badBehaOjb: any = {
          factorList: res.data.badDrivingHabits.factorList,
          totalScore: res.data.badDrivingHabits.totalScore,
        };
        badBehaOjb.factorList.unshift({
          factorName: '驾驶陋习',
          score: '',
          isFirst: true,
        });
        badBehaOjb.factorList.push({
          factorName: '驾驶陋习合计',
          score: res.data.badDrivingHabits.totalScore,
          isTotal: true,
        });

        const safetyOjb: any = {
          factorList: res.data.activeSafety.factorList,
          totalScore: res.data.activeSafety.totalScore,
        };
        safetyOjb.factorList.unshift({
          factorName: '主动安全相关',
          score: '',
          isFirst: true,
        });
        safetyOjb.factorList.push({
          factorName: '主动安全合计',
          score: res.data.activeSafety.totalScore,
          isTotal: true,
        });

        const speedOjb: any = {
          factorList: res.data.speedDependent.factorList,
          totalScore: res.data.speedDependent.totalScore,
        };
        speedOjb.factorList.unshift({
          factorName: '速度相关',
          score: '',
          isFirst: true,
        });
        speedOjb.factorList.push({
          factorName: '速度相关合计',
          score: res.data.speedDependent.totalScore,
          isTotal: true,
        });

        selfList.push(selfOjb);
        dealOrange(selfList, selfOjb);
        setSelfList([...selfList]);
        selfAllList = [...selfList];

        badBehaList.push(badBehaOjb);
        dealOrange(badBehaList, badBehaOjb);
        setBadBehaList([...badBehaList]);
        badBehaAllList = [...badBehaList];

        safetyList.push(safetyOjb);
        dealOrange(safetyList, safetyOjb);
        setSafetyList([...safetyList]);
        safetyAllList = [...safetyList];

        speedList.push(speedOjb);
        dealOrange(speedList, speedOjb);
        setSpeedList([...speedList]);
        speedAllList = [...speedList];
        setLoading(false);
      }
    });
  };
  // 删除一项
  const delRowApi = (data: any) => {
    if (topList.length < 2) return message.warning('至少选择一个司机');
    if (showDiffStatus) showAllFactor();
    const delIndex = topList.findIndex((el: any) => el.driverId == data.driverId);
    topList.splice(delIndex, 1);
    setTopList([...topList]);
    seltedIdArrs.splice(delIndex, 1);
    setSeltedIdArrs([...seltedIdArrs]);
    selfList.splice(delIndex, 1);
    setSelfList([...selfList]);
    selfAllList = [...selfList];

    badBehaList.splice(delIndex, 1);
    setBadBehaList([...badBehaList]);
    badBehaAllList = [...badBehaList];

    safetyList.splice(delIndex, 1);
    setSafetyList([...safetyList]);
    safetyAllList = [...safetyList];

    speedList.splice(delIndex, 1);
    setSpeedList([...speedList]);
    speedAllList = [...speedList];
  };
  const addDriver = () => {
    // setModalType('matter');
    setIsModalShow({ show: true, modelType: 'addDriver' });
    setConfigModal({
      title: '添加人员',
      children: (
        <AddSearchDriverComp
          ref={addSearchDriverRef}
          addRow={addRowApi}
          delRow={delRowApi}
          seltedIds={JSON.stringify(seltedIdArrs)}
        />
      ),
    });
  };
  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };
  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 900,
    centered: true,
    destroyOnClose: true,
    footer: [
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={closeModal}>
        关闭
      </Button>,
    ],
    onCancel: closeModal,
  };
  useEffect(() => {
    setTargetOffset(topRef.current?.clientHeight);
    const nowDriver = urlSearch.get('driverObj') || '';
    addRowApi(JSON.parse(nowDriver)); // 默认加第一项
  }, []);
  // 查看差异
  const seeShowDiff = () => {
    if (topList.length < 2) return message.warning('请至少选择两条数据');
    setShowDiffStatus(true);

    // 四种全部分别给他对比出来
    const dealArr = [selfList, badBehaList, safetyList, speedList];
    dealArr.forEach((el, index5) => {
      const copySelfArr = [...el];
      const newSelfArr: any = [];
      // 对司机自身arr进行遍历，然后因子list再遍历。
      copySelfArr.forEach((el, index) => {
        const newObj = {
          factorList: [] as any,
        };
        el.factorList.forEach((item: any, index2: number) => {
          let ifpush = false;
          // 再跟司机自身arr进行遍历
          copySelfArr.forEach((el2, index3) => {
            // 不是当前索引的(其他列)
            if (index != index3) {
              el2.factorList.forEach((item2: any, index4: number) => {
                // 对应因子对比，相同的因子，并且分数有一个不同。对应就是差异
                if (index5 == 0 && item2.factorName != '司机相关合计') {
                  if (index2 == index4 && item2.score != item.score) ifpush = true;
                }
                if (index5 == 1 && item2.factorName != '驾驶陋习合计') {
                  if (index2 == index4 && item2.score != item.score) ifpush = true;
                }
                if (index5 == 2 && item2.factorName != '主动安全合计') {
                  if (index2 == index4 && item2.score != item.score) ifpush = true;
                }
                if (index5 == 3 && item2.factorName != '速度相关合计') {
                  if (index2 == index4 && item2.score != item.score) ifpush = true;
                }
              });
            }
          });
          // 然后因子push进去
          if (ifpush) newObj.factorList.push(item);
        });
        newObj.factorList.unshift({
          factorName:
            index5 == 0
              ? '司机相关'
              : index5 == 1
              ? '驾驶陋习'
              : index5 == 2
              ? '主动安全相关'
              : index5 == 3
              ? '速度相关'
              : '',
          score: '',
          isFirst: true,
        });
        newObj.factorList.push({
          factorName:
            index5 == 0
              ? '司机相关合计'
              : index5 == 1
              ? '驾驶陋习合计'
              : index5 == 2
              ? '主动安全合计'
              : index5 == 3
              ? '速度相关合计'
              : '',
          score: el.totalScore,
          isTotal: true,
        });
        // push对应司机
        newSelfArr.push(newObj);
      });
      if (index5 == 0) setSelfList(newSelfArr);
      else if (index5 == 1) setBadBehaList(newSelfArr);
      else if (index5 == 2) setSafetyList(newSelfArr);
      else if (index5 == 3) setSpeedList(newSelfArr);
    });
  };
  return (
    <div
      id="LayoutContent"
      className={Ostyle.safe_drive_compar_sty}
      style={{ position: 'relative', paddingRight: 20, height: '100%', overflowY: 'scroll', overflowX: 'hidden' }}
    >
      <Spin
        spinning={loading}
        style={{ position: 'absolute', left: 0, right: 0, width: '100%', height: '100%', zIndex: 999 }}
      ></Spin>
      <div style={{ display: 'flex' }}>
        <div style={{ padding: 20, width: 160, minWidth: 160 }}>
          <div id="leftLinkBtn" className={Ostyle.left_cont}>
            <Anchor
              getContainer={getCont}
              targetOffset={targetOffset}
              items={[
                {
                  key: 'key0',
                  href: '#link_0',
                  title: '司机自身',
                },
                {
                  key: 'key1',
                  href: '#link_1',
                  title: '驾驶陋习',
                },
                {
                  key: 'key2',
                  href: '#link_2',
                  title: '主动安全',
                },
                {
                  key: 'key3',
                  href: '#link_3',
                  title: '速度相关',
                },
              ]}
            />
            {!showDiffStatus ? (
              <div
                className={`${Ostyle.left_bot} ${Ostyle.show_diff_btn}`}
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  seeShowDiff();
                }}
              >
                展示差异指标
              </div>
            ) : (
              <div
                className={`${Ostyle.left_bot}  ${Ostyle.hide_diff_btn}`}
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  showAllFactor();
                }}
              >
                展示全部指标
              </div>
            )}
          </div>
        </div>
        {/* <div style={{ width: 'calc(100% - 180px)', display: 'flex', overflowX: 'scroll' }}> */}
        <div style={{ height: '100%', width: 'calc(100% - 140px)' }}>
          <div id="mainContDom" className={Ostyle.mian_cont} ref={contentRef}>
            <div id="link_0" className={`${Ostyle.cont_body} ${Ostyle.con_1}`} style={{ marginTop: 210 }}>
              <div className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                {selfList[0]?.factorList.map((item: any, index2: number) => {
                  return (
                    <div
                      key={index2}
                      style={{
                        fontWeight: item.isFirst || item.isTotal ? 'bold' : '',
                        fontSize: item.isFirst ? 16 : item.isTotal ? 14 : '',
                        color: item.isTotal ? '#409eff' : '',
                      }}
                      title={
                        !item.isFirst && !item.isTotal ? `${item.factorName} (${item.maxScore})` : `${item.factorName}`
                      }
                    >
                      {item.factorName}
                      {!item.isFirst && !item.isTotal ? <>({item.maxScore})</> : ''}
                    </div>
                  );
                })}
              </div>
              {selfList?.map((el: any, index: number) => {
                return (
                  <div key={index} className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                    {el.factorList.map((item: any, index2: number) => {
                      return (
                        <div
                          key={index2}
                          style={{
                            fontWeight: item.isTotal || item.color == 'orange' ? 'bold' : '',
                            fontSize: item.isTotal ? 16 : '',
                            color: item.color == 'orange' ? '#ff6d3b' : '',
                          }}
                        >
                          {item.score}
                        </div>
                      );
                    })}
                  </div>
                );
              })}
              <div className={`${Ostyle.cont_li}`}>
                {selfList[0]?.factorList.map((item: any, index2: number) => {
                  return <div key={index2}></div>;
                })}
              </div>
            </div>

            <div id="link_1" className={`${Ostyle.cont_body} ${Ostyle.con_2}`}>
              <div className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                {badBehaList[0]?.factorList.map((item: any, index2: number) => {
                  return (
                    <div
                      key={index2}
                      style={{
                        fontWeight: item.isFirst || item.isTotal ? 'bold' : '',
                        fontSize: item.isFirst ? 16 : item.isTotal ? 14 : '',
                        color: item.isTotal ? '#409eff' : '',
                      }}
                      title={
                        !item.isFirst && !item.isTotal ? `${item.factorName} (${item.maxScore})` : `${item.factorName}`
                      }
                    >
                      {item.factorName}
                      {!item.isFirst && !item.isTotal ? <>({item.maxScore})</> : ''}
                    </div>
                  );
                })}
              </div>
              {badBehaList?.map((el: any, index: number) => {
                return (
                  <div key={index} className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                    {el.factorList.map((item: any, index2: number) => {
                      return (
                        <div
                          key={index2}
                          style={{
                            fontWeight: item.isTotal || item.color == 'orange' ? 'bold' : '',
                            fontSize: item.isTotal ? 16 : '',
                            color: item.color == 'orange' ? '#ff6d3b' : '',
                          }}
                        >
                          {item.score}
                        </div>
                      );
                    })}
                  </div>
                );
              })}
              <div className={`${Ostyle.cont_li}`}>
                {badBehaList[0]?.factorList.map((item: any, index2: number) => {
                  return <div key={index2}></div>;
                })}
              </div>
            </div>

            <div id="link_2" className={`${Ostyle.cont_body} ${Ostyle.con_3}`}>
              <div className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                {safetyList[0]?.factorList.map((item: any, index2: number) => {
                  return (
                    <div
                      key={index2}
                      style={{
                        fontWeight: item.isFirst || item.isTotal ? 'bold' : '',
                        fontSize: item.isFirst ? 16 : item.isTotal ? 14 : '',
                        color: item.isTotal ? '#409eff' : '',
                      }}
                      title={
                        !item.isFirst && !item.isTotal ? `${item.factorName} (${item.maxScore})` : `${item.factorName}`
                      }
                    >
                      {item.factorName}
                      {!item.isFirst && !item.isTotal ? <>({item.maxScore})</> : ''}
                    </div>
                  );
                })}
              </div>
              {safetyList?.map((el: any, index: number) => {
                return (
                  <div key={index} className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                    {el.factorList.map((item: any, index2: number) => {
                      return (
                        <div
                          key={index2}
                          style={{
                            fontWeight: item.isTotal || item.color == 'orange' ? 'bold' : '',
                            fontSize: item.isTotal ? 16 : '',
                            color: item.color == 'orange' ? '#ff6d3b' : '',
                          }}
                        >
                          {item.score}
                        </div>
                      );
                    })}
                  </div>
                );
              })}
              <div className={`${Ostyle.cont_li}`}>
                {safetyList[0]?.factorList.map((item: any, index2: number) => {
                  return <div key={index2}></div>;
                })}
              </div>
            </div>

            <div id="link_3" className={`${Ostyle.cont_body} ${Ostyle.con_4}`}>
              <div className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                {speedList[0]?.factorList.map((item: any, index2: number) => {
                  return (
                    <div
                      key={index2}
                      style={{
                        fontWeight: item.isFirst || item.isTotal ? 'bold' : '',
                        fontSize: item.isFirst ? 16 : item.isTotal ? 14 : '',
                        color: item.isTotal ? '#409eff' : '',
                      }}
                      title={
                        !item.isFirst && !item.isTotal ? `${item.factorName} (${item.maxScore})` : `${item.factorName}`
                      }
                    >
                      {item.factorName}
                      {!item.isFirst && !item.isTotal ? <>({item.maxScore})</> : ''}
                    </div>
                  );
                })}
              </div>
              {speedList?.map((el: any, index: number) => {
                return (
                  <div key={index} className={`${Ostyle.cont_li} ${Ostyle.cont_tr}`}>
                    {el.factorList.map((item: any, index2: number) => {
                      return (
                        <div
                          key={index2}
                          style={{
                            fontWeight: item.isTotal || item.color == 'orange' ? 'bold' : '',
                            fontSize: item.isTotal ? 16 : '',
                            color: item.color == 'orange' ? '#ff6d3b' : '',
                          }}
                        >
                          {item.score}
                        </div>
                      );
                    })}
                  </div>
                );
              })}
              <div className={`${Ostyle.cont_li}`}>
                {speedList[0]?.factorList.map((item: any, index2: number) => {
                  return <div key={index2}></div>;
                })}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div id="topContFixed" className={Ostyle.main_top} ref={topRef}>
        <div className={Ostyle.top_left} style={{ width: 160, minWidth: 160 }}></div>
        <div style={{ position: 'fixed', width: 160, height: 220, left: 0, background: '#f5f5f5', zIndex: 99999 }}>
          <Button
            icon={<LeftOutlined />}
            style={{ marginLeft: 10, marginTop: 10 }}
            onClick={() => {
              navigator('/safeIndex/safeIndexStatistics/driverIndex');
            }}
          >
            退出对比
          </Button>
        </div>
        <div className={Ostyle.top_right}>
          <div className={`${Ostyle.top_li} ${Ostyle.top_tr}`}>
            <div>姓名</div>
            <div className={Ostyle.cont_height}>得分情况</div>
            <div>星级评定</div>
          </div>
          {topList.map((el: any, index: number) => {
            return (
              <div key={index} className={`${Ostyle.top_li} ${Ostyle.top_cont_li}`}>
                <div>{el.driverName || '--'}</div>
                <div className={Ostyle.cont_height}>
                  <ScoreDimensionCmp cmpdata={el} />
                </div>

                <div>{el.starRating || 0}星</div>
                <span
                  className={Ostyle.del_person}
                  onClick={() => {
                    delRowApi(el);
                  }}
                >
                  ×
                </span>
              </div>
            );
          })}
          <div className={`${Ostyle.top_li}`}>
            <div></div>
            <div className={Ostyle.add_cont}>
              <img
                className={Ostyle.add_btn}
                src={iconAdd}
                width={80}
                height={80}
                onClick={() => {
                  addDriver();
                }}
              />
              <span>添加人员</span>
            </div>
            <div></div>
          </div>
        </div>
      </div>
      <CusModal {...modalConst} {...configModal} />
    </div>
  );
};

export default SafeDriverComparison;
